package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.constant.CacheConstants;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.utils.AssertUtil;
import cn.itsource.ymcc.utils.StrUtils;
import cn.itsource.ymcc.vo.SMSRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;



    @Override
    public JsonResult getImgCode(String imgKey) {
        //1.参数校验
        AssertUtil.isTrue(StringUtils.hasText(imgKey),"图形验证码key不能为空！");

        //2.图形验证码 糊涂工具包
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
        String imageCode = captcha.getCode();

        //3.存储到Redis中 3分钟过期
        redisTemplate.opsForValue().set(imgKey,imageCode,3, TimeUnit.MINUTES);

        //4.获取base64编码字符串 放入JsonResult的data属性中返回给前端
        String imageBase64 = captcha.getImageBase64();
        return JsonResult.success().setData(imageBase64);
    }

    @Override
    public JsonResult sendSmsCode(SMSRegisterVO registerVO) {
        //判断验证码是否存在
        AssertUtil.isTrue(redisTemplate.hasKey(registerVO.getImgKey()),"图片验证码已过期");
        //验证验证码是否正确
        String code = (String) redisTemplate.opsForValue().get(registerVO.getImgKey());
        AssertUtil.isTrue(registerVO.getImgCode().equalsIgnoreCase(code),"图片验证码不正确");
        //发送验证码
        String phoneCode = StrUtils.getComplexRandomString(6);
        //5 = 300
        if(redisTemplate.hasKey(CacheConstants.REGISTER_PREFIX+registerVO.getMobile())){
            Long expire = redisTemplate.getExpire(registerVO.getMobile(), TimeUnit.SECONDS);
            if(expire > 240){
                return JsonResult.error("慢点");
            }
            phoneCode = (String)redisTemplate.opsForValue().get(CacheConstants.REGISTER_PREFIX+registerVO.getMobile());
        }
        System.out.println(phoneCode);
        redisTemplate.opsForValue().set(CacheConstants.REGISTER_PREFIX+registerVO.getMobile(),phoneCode,5,TimeUnit.MINUTES);
        return JsonResult.success();
    }
}
